import { _decorator, AudioClip, AudioSource, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager {
    static _instance: AudioManager;
    static get instance() {
        if (this._instance == null) {
            this._instance = new AudioManager();
        }
        return this._instance;
    }
    playAudio(audio: AudioClip, loop: boolean = false, nodeAudio: Node) {
        if (audio) {
            // 动态创建一个独立的 AudioSource
            const tempNode = new Node("TempAudioSource");
            tempNode.parent = nodeAudio;

            const tempAudioSource = tempNode.addComponent(AudioSource);

            // 设置音频剪辑和是否循环
            tempAudioSource.clip = audio;
            tempAudioSource.loop = loop;

            if (loop) {
                // 如果循环播放，直接使用 play()
                tempAudioSource.play();
            } else {
                // 如果非循环播放，使用 playOneShot
                tempAudioSource.playOneShot(audio, 1.0);

                // 在音频播放结束后销毁临时节点
                setTimeout(() => {
                    tempNode.destroy();
                }, audio.getDuration() * 1000);
            }
        } else {
            console.error("AudioClip is missing.");
        }
    }

    stopAudioOnce(audio: AudioClip, nodeAudio: Node) {
        // 查找并销毁所有与该音频相关的临时节点
        const children = nodeAudio.children;
        for (const child of children) {
            const audioSource = child.getComponent(AudioSource);
            if (audioSource && audioSource.clip === audio) {
                child.destroy(); // 销毁临时节点
            }
        }
    }
}


